# TriggerSwitchD, executes commands to activate/deactive remote switches.
# (c) Copyright 2010 Pontus Strömdahl, AdhocSkill. 
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

module TriggerSwitchD
  module IPC
    #unix socket thread, see README.rdoc for usage
    def self.create(socket_path)
      File.delete(socket_path) if File.exist? socket_path
      sock = UNIXServer.open(socket_path)
      Thread.start(sock) do |sock|
        outer_loop(sock)
      end
    end
    
    private
    
    def self.outer_loop(sock)
      current_thread = Thread.current
      while(!["stop"].include?(current_thread["received"]))
        current_thread["received"] = ""
        accepted_socket = sock.accept
        inner_loop(accepted_socket)
      end
    end

    def self.inner_loop(sock)
      current_thread = Thread.current
      while(!["stop","bye"].include?(current_thread["received"]))
        wait_and_receive_from(sock)
        wait_for_command_to_process
        send_response(sock)
        receive_connection_lost
      end
    end
    
    def self.receive_connection_lost
      current_thread = Thread.current
      current_thread["received"] = "bye" if current_thread["received"] == ""
    end
    
    def self.send_response(sock)
      current_thread = Thread.current
      sock.send(current_thread["response"],0) unless current_thread["received"] == ""
    end
    
    def self.wait_and_receive_from(sock)
      current_thread = Thread.current
      current_thread["received"] = sock.recvfrom(200)[0]
    end
    
    def self.wait_for_command_to_process
      current_thread = Thread.current
      received_str = current_thread["received"]
      Thread.stop unless ["bye",""].include?(received_str)
      current_thread["response"] = "bye" if received_str == "bye"
    end
  end
end